//
//  SigninViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/10.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "SigninViewController.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "UILabel+YBAttributeTextTapAction.h"
#import "SigninAccountViewController.h"
#import "IDSelectViewController.h"
#import "AppDelegate.h"
#import "PersonalTabBarController.h"
#import "CompanyTabBarController.h"
#import "PrivacyPolicyAlertView.h"

#import "FindPwdViewController.h"
//#import "ResetPwdViewController.h"
#import "RegisterViewController.h"
#import "SigninForCaptchaViewController.h"

#import "AESEnrypt.h"
#import "NSString+AES.h"
#import "TUIKit.h"
#import "GuidePageView.h"

#import "PMineResumeViewController.h"
//#import "ResignAgreementViewController.h"
#import "CompanyFirstInfoViewController.h"
#import "PersonalWorkExperienceViewController.h"
#import "CompanySecondInfoViewController.h"
#import "PersonalFirstInfoViewController.h"
#import "PersonalEducationInfoViewController.h"
#import "GeneralWebViewViewController.h"
#import "CompanyInfoViewController.h"
#import "ShareItemButton.h"
#import "WXBindingViewController.h"
#import "WXAuth.h"

#import "WXBindingViewController.h"

@interface SigninViewController ()<UITextFieldDelegate, PrivacyPolicyAlertViewDelegate, GuidePageViewDelegate,ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding>
{
    UITextField *phoneTextField;
    UITextField *passwordTextField;
    GuidePageView *guidePageS;
    NSString *recordStr;

}
@end

@implementation SigninViewController

- (void)privacyPolicyAlertViewBrowseOrOkTap:(PrivacyPolicyAlertView *)privacyPolicyAlertView {
    [privacyPolicyAlertView removeFromSuperview];
}
- (void)privacyPolicyAlertView:(PrivacyPolicyAlertView *)privacyPolicyAlertView tapItem:(GeneralWebViewType)type {
    [privacyPolicyAlertView removeFromSuperview];
    [self showTiaokuan:type];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [DataToolsControl sharedManager].openSigninType = OpenSigninTypeOfWXSignin;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationWXCode:) name:NotificationForWXCode object:nil];
    
    [self initUI];
    
    if (!FirstUse) {
        PrivacyPolicyAlertView *alertView = [[PrivacyPolicyAlertView alloc] initWithTarget:self];
        
        guidePageS = [[GuidePageView alloc] init];
        guidePageS.delegate = self;
        [[UIApplication sharedApplication].keyWindow addSubview:guidePageS];
        UD_SetOForK(isYes, isFirstUse);
    }
}
- (void)guidePageCallback {
    [guidePageS removeFromSuperview];
    guidePageS = nil;
}
- (void)initUI {
    self.navigationItem.title = @"欢迎来到比特聘";
    
    /*
    if ([DataToolsControl sharedManager].appJustOpen) { // 刚打开
        UIButton *closeBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-50*Scale, HeightOfStatusBar+3, 50*Scale, 36) imageName:nil target:self action:@selector(closeBtnTap) title:@"关闭" titleColor:THEMECOLOR_OF_ORANGE];
        closeBtn.titleLabel.font = Font(Font_15);
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:closeBtn];
        self.navigationItem.rightBarButtonItem = rightItem;
    } else {
        self.leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.leftButton.frame = CGRectMake(0, 0, 44, 44);
        self.leftButton.imageEdgeInsets = UIEdgeInsetsMake(11, 0, 12, 32);
        [self.leftButton setImage:[UIImage imageNamed:@"back_b"] forState:UIControlStateNormal];
        [self.leftButton addTarget:self action:@selector(customBackButtonTap) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
        self.navigationItem.leftBarButtonItem = backItem;
    }
    */
//    UIButton *closeBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-50*Scale, HeightOfStatusBar+3, 50*Scale, 36) imageName:nil target:self action:@selector(closeBtnTap) title:@"关闭" titleColor:THEMECOLOR_OF_ORANGE];
//    closeBtn.titleLabel.font = Font(Font_15);
//    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:closeBtn];
//    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.leftButton.frame = CGRectMake(0, 0, 44, 44);
//    self.leftButton.imageEdgeInsets = UIEdgeInsetsMake(11, 0, 12, 32);
    [self.leftButton setImage:[UIImage imageNamed:@"back_b"] forState:UIControlStateNormal];
    [self.leftButton addTarget:self action:@selector(closeBtnTap) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
//    self.navigationItem.leftBarButtonItem = backItem;
    
    
    
    UIImageView *topBbImgView = [UIToolsControl initImageViewWithFrame:CGRectMake(0, 0, WIDTH, 160*Scale) imageName:@"signin_top_bg"];
    [self.view addSubview:topBbImgView];
    
    topBbImgView.frame = CGRectMake(0, 0, WIDTH, 50*Scale);
    topBbImgView.hidden = YES;
    
//    UILabel *topLbl = [UIToolsControl initLabelWithFrame:CGRectMake(0, 80*Scale, WIDTH*0.6, 40*Scale) text:@"欢迎来到比特聘" textColor:COLOR_OF_WHITE font:Font_25];
//    topLbl.font = FontBold(Font_25);
//    topLbl.textAlignment = NSTextAlignmentCenter;
//    [topBbImgView addSubview:topLbl];
//    UILabel *topTwoLbl = [UIToolsControl initLabelWithFrame:CGRectMake(0, EndY(topLbl), WIDTH*0.6, 30*Scale) text:@"共识 共建 共营 共赢" textColor:COLOR_OF_WHITE font:Font_14];
//    topTwoLbl.textAlignment = NSTextAlignmentCenter;
//    [topBbImgView addSubview:topTwoLbl];
    
    
    phoneTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, EndY(topBbImgView)+25*Scale, WIDTH-60*Scale, 50*Scale) placeholder:@"请输入账号" secureTextEntry:NO font:Font_17 padding:YES];
    [phoneTextField borderColor:THEMECOLOR_OF_TEXT_cccccc borderWidth:lineH borderType:BorderSideTypeBottom];
    phoneTextField.delegate = self;
//    phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:phoneTextField];
    
    passwordTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, EndY(phoneTextField)+25*Scale, WIDTH-60*Scale, 50*Scale) placeholder:PasswordPlaceholderText secureTextEntry:YES font:Font_17 padding:YES];
    [passwordTextField borderColor:THEMECOLOR_OF_TEXT_cccccc borderWidth:lineH borderType:BorderSideTypeBottom];
    passwordTextField.delegate = self;
    passwordTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.view addSubview:passwordTextField];
     
//    UIButton *forgetPwdBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-100*Scale, EndY(passwordTextField), 80*Scale, 40*Scale) imageName:nil target:self action:@selector(forgetPwdBtnTap) title:@"忘记密码?" titleColor:THEMECOLOR_OF_TEXT_333333];
//    forgetPwdBtn.titleLabel.font = Font(Font_14);
//    [self.view addSubview:forgetPwdBtn];
    
    
    UIButton *okBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, EndY(passwordTextField)+50*Scale, WIDTH-80*Scale, 46*Scale) imageName:nil target:self action:@selector(okBtnTap) title:@"登录" titleColor:COLOR_OF_WHITE];
    okBtn.titleLabel.font = FontBold(Font_17);
    okBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    okBtn.layer.cornerRadius = 23*Scale;
    okBtn.layer.masksToBounds = YES;
    [self.view addSubview:okBtn];
    
    UIButton *captchaSigninBtn = [UIToolsControl initButtonWithFrame:CGRectMake(StartX(okBtn), EndY(okBtn)+10*Scale, 90*Scale, 40*Scale) imageName:nil target:self action:@selector(captchaSigninBtnTap) title:@"验证码登录" titleColor:THEMECOLOR_OF_TEXT_333333];
    captchaSigninBtn.titleLabel.font = Font(Font_14);
//    captchaSigninBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.view addSubview:captchaSigninBtn];
    
    UIButton *forgetPwdBtn = [UIToolsControl initButtonWithFrame:CGRectMake(EndX(captchaSigninBtn), StartY(captchaSigninBtn), 80*Scale, 40*Scale) imageName:nil target:self action:@selector(forgetPwdBtnTap) title:@"忘记密码?" titleColor:THEMECOLOR_OF_TEXT_333333];
    forgetPwdBtn.titleLabel.font = Font(Font_14);
    [self.view addSubview:forgetPwdBtn];
    
    //    @"手机验证码注册/登录"
    UIButton *registerBtn = [UIToolsControl initButtonWithFrame:CGRectMake(EndX(okBtn)-60*Scale, StartY(captchaSigninBtn), 60*Scale, 40*Scale) imageName:nil target:self action:@selector(registerBtnTap) title:@"注册" titleColor:THEMECOLOR_OF_ORANGE];
    registerBtn.titleLabel.font = Font(Font_14);
//    registerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.view addSubview:registerBtn];
    
    CGFloat itemWidth = (WIDTH-20*Scale)*0.25;
//    ShareItemButton *wxSigninBtn = [[ShareItemButton alloc] initWithFrame:CGRectMake((WIDTH-itemWidth)*0.5, EndY(captchaSigninBtn)+50*Scale, itemWidth, 120*Scale) imageName:@"share_weixin_haoyou" itemText:@"微信登录"];
    ShareItemButton *wxSigninBtn = [[ShareItemButton alloc] initWithFrame:CGRectMake((WIDTH-itemWidth)*0.5-(50*Scale), HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-200*Scale, itemWidth, 120*Scale) imageName:@"share_weixin_haoyou" itemText:@"微信登录"];
    [wxSigninBtn addTarget:self action:@selector(wxSigninBtnTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:wxSigninBtn];
    
    ShareItemButton *appleSigninBtn = [[ShareItemButton alloc] initWithFrame:CGRectMake((WIDTH-itemWidth)*0.5+(50*Scale), HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-200*Scale, itemWidth, 120*Scale) imageName:@"login_apple" itemText:@"Apple登录"];
    [appleSigninBtn addTarget:self action:@selector(appleSigninBtnTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:appleSigninBtn];
    
    if(!iOS13){
        wxSigninBtn.v_x = (WIDTH-itemWidth)*0.5;
        appleSigninBtn.hidden = YES;
    }
    if(![UIToolsControl canOpenWXApp]){
        wxSigninBtn.hidden = YES;
        appleSigninBtn.v_x = (WIDTH-itemWidth)*0.5;
        appleSigninBtn.hidden = YES;
//        appleSigninBtn.hidden = YES;
    }

    
    NSString *clauseString = @"登录即代表您已同意我们的《服务协议》和《隐私政策》";
    CGFloat clauseStrWidth = [UIToolsControl textWidth:clauseString size:CGSizeMake(MAXFLOAT, 40*Scale) font:Font_13]+1;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:clauseString];
    [attributedString addAttribute:NSFontAttributeName value:Font(Font_13) range:NSMakeRange(0, clauseString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_TEXT_666666 range:NSMakeRange(0, clauseString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_ORANGE range:NSMakeRange(12, 13)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_TEXT_666666 range:NSMakeRange(18, 1)];
    UILabel *clauseLabel = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH-clauseStrWidth)*0.5, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-60*Scale, clauseStrWidth, 40*Scale)];
    clauseLabel.font = Font(Font_13);
    clauseLabel.backgroundColor = COLOR_OF_CLEAR;
    clauseLabel.attributedText = attributedString;
    clauseLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:clauseLabel];
    __weak __typeof(self)weakSelf = self;
    [clauseLabel yb_addAttributeTapActionWithStrings:@[@"《服务协议》", @"《隐私政策》"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if ([string isEqualToString:@"《服务协议》"]) {
            NSLog(@"服务协议");
            [strongSelf showTiaokuan:GeneralWebViewTypeOfResignAgreement];
        } else {
            NSLog(@"隐私政策");
            [strongSelf showTiaokuan:GeneralWebViewTypeOfPrivacyPolicy];
        }
    }];
    
    /*
    UIButton *captchaSigninBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, HEIGHT-HeightOfStatusBarAndNavigationBar-HeightOfTabBarSafeMargin-70*Scale, 160*Scale, 40*Scale) imageName:nil target:self action:@selector(captchaSigninBtnTap) title:@"手机验证码登录" titleColor:THEMECOLOR_OF_TEXT_333333];
    captchaSigninBtn.titleLabel.font = Font(Font_15);
    captchaSigninBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.view addSubview:captchaSigninBtn];
    
    //    @"手机验证码注册/登录"
    UIButton *registerBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-200*Scale, HEIGHT-HeightOfStatusBarAndNavigationBar-HeightOfTabBarSafeMargin-70*Scale, 160*Scale, 40*Scale) imageName:nil target:self action:@selector(registerBtnTap) title:@"账号注册" titleColor:THEMECOLOR_OF_TEXT_333333];
    registerBtn.titleLabel.font = Font(Font_15);
    registerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.view addSubview:registerBtn];
    */
    
//    PrivacyPolicyAlertView *alertView = [[PrivacyPolicyAlertView alloc] initWithTarget:self];
}
- (void)showTiaokuan:(GeneralWebViewType)showType {
    GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
    GWVC.showType = showType;
    GWVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:GWVC animated:YES];
}
- (void)wxSigninBtnTap {
    if ([UIToolsControl canOpenWXApp]) {
        [WXAUTH sendWXAuthReq];
    } else {
        SVPHUDError(@"您还没有安装微信，请先安装微信");
    }
}

- (void)appleSigninBtnTap {
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc]init];
        ASAuthorizationAppleIDRequest * request = [provider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName,ASAuthorizationScopeEmail];
        ASAuthorizationController *vc= [[ASAuthorizationController alloc]initWithAuthorizationRequests:@[request]];
        vc.delegate = self;
        vc.presentationContextProvider = self;
        [vc performRequests];
    } else {
        // Fallback on earlier versions
    }
    
}



- (void)notificationWXCode:(NSNotification *)notification {
    if ([DataToolsControl sharedManager].openSigninType != OpenSigninTypeOfWXSignin) {
        return;
    }
    NSString *code = [NSString stringWithFormat:@"%@", notification.userInfo[@"code"]];
    NSLog(@"%@", code);
    
    if (![code isEqualToString:UD_GetOForK(isOpenWXSigninCode)]) {
        return;
    }
    if ([DataToolsControl sharedManager].codeRecord != 1) {
        return;
    }
    [DataToolsControl sharedManager].codeRecord++;
    
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    if([DataToolsControl sharedManager].isApple){
        [dic setObject:@"apple" forKey:@"type"];
    }else{
        [dic setObject:@"weixin" forKey:@"type"];
    }
    [dic setObject:code forKey:@"code"];
    [dic setObject:@"" forKey:@"token"];
    
    [BaseNetManager requestWithMethod:POST path:User_OpenSignin_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDDismiss;
            id data = responseObject[@"data"];
            if ([data isKindOfClass:[NSDictionary class]] && ([data count]>0)) {
                [self detailDataAndPushVC:responseObject];
                
                [DataToolsControl autoLogin];
            } else {
                WXBindingViewController *WXBVC = [[WXBindingViewController alloc] init];
                [self.navigationController pushViewController:WXBVC animated:YES];
            }
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)okBtnTap {
    [UIToolsControl resignFirstResponderForTextFieldArray:@[phoneTextField, passwordTextField]];
    if (phoneTextField.text.length>0) {
        if (passwordTextField.text.length>=6) {
            [self upDate];
        } else {
            SVPHUDError(PasswordAlertText);
            [passwordTextField becomeFirstResponder];
        }
//        if ([UIToolsControl validatePhoneNumber:phoneTextField.text]) {
//            if (passwordTextField.text.length>=6) {
//                [self upDate];
//            } else {
//                SVPHUDError(PasswordAlertText);
//                [passwordTextField becomeFirstResponder];
//            }
//        } else {
//            SVPHUDError(PhoneNumberOKAlertText);
//            [phoneTextField becomeFirstResponder];
//        }
    } else {
        SVPHUDError(PhoneNumberAlertText);
        [phoneTextField becomeFirstResponder];
    }
}
- (void)upDate {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phoneTextField.text forKey:@"username"];
    recordStr = [passwordTextField.text aci_encryptWithAES];
    [dic setObject:recordStr forKey:@"password"];
    
    [BaseNetManager requestWithMethod:POST path:Signin_Pwd_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            self->passwordTextField.text = nil;
            UD_SetOForK(isYes, isSignin);
            UDSynchronize;

            [self signinLoadData:responseObject];
            [AppDelegate loadLocationData];
            [self detailDataAndPushVC:responseObject];
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)detailDataAndPushVC:(NSDictionary *)responseObject {
    [DataToolsControl dataAnalysisUserInfo:responseObject];
    
    NSLog(@"kkkkkkk:::::%@", UD_GetOForK(isSignin));
    UD_SetOForK(isYes, isSignin);
    UDSynchronize;
    NSLog(@"lllllll:::::%@", UD_GetOForK(isSignin));
    
//      [DataToolsControl autoLoginForInitIM];
    [DataToolsControl initIMPeizhi];
    [AppDelegate loadLocationData];
    
    NSDictionary *data = responseObject[@"data"];
    if (data[@"user_guide"] && [data[@"user_guide"] length] && ([data[@"user_guide"] isEqualToString:@"choose_role"])) { // 用户还没选角色 （选择用户角色）
        IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
        IDSVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:IDSVC animated:NO];
    } else {
        if ([data[@"user_guide"] isEqualToString:@"company_add_job"]) { // 添加招聘职位
            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                [SharedApp showViewController:TabBarTypeOfCompany];
                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                tabBarController.selectedIndex = 1;
            }];
        } else if ([data[@"user_guide"] isEqualToString:@"company_create"]) { // 招聘者下面没有企业的话就会引导创建
            CompanyFirstInfoViewController *IDSVC = [[CompanyFirstInfoViewController alloc] init];
            IDSVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:IDSVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"company_info"]) { // 填写企业信息
            CompanySecondInfoViewController *IDSVC = [[CompanySecondInfoViewController alloc] init];
            IDSVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:IDSVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"company_audit"]) { // 企业未认证
            SVPHUDShow;
            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                SVPHUDDismiss;
                [SharedApp showViewController:TabBarTypeOfCompany];
                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                tabBarController.selectedIndex = tabBarController.viewControllers.count-1;
                RootNavigationController *navigationController = (RootNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                
                CompanyInfoViewController *CIVC = [[CompanyInfoViewController alloc] init];
                CIVC.hidesBottomBarWhenPushed = YES;
                [navigationController pushViewController:CIVC animated:YES];
            }];
        } else if (([data[@"user_guide"] isEqualToString:@"resume_create"])) { // 创建简历页
            PersonalFirstInfoViewController *PMRVC = [[PersonalFirstInfoViewController alloc] init];
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"resume_edu"]) { // 完善简历中教育经历
            if (data[@"is_graduate"] && ([data[@"is_graduate"] integerValue] == 0)) {
                [DataToolsControl sharedManager].idType = IDTypeOfWorker;
            } else {
                [DataToolsControl sharedManager].idType = IDTypeOfFreshGraduate;
            }
            
            PersonalEducationInfoViewController *PMRVC = [[PersonalEducationInfoViewController alloc] init];
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"resume_work"]) { // 完善简历中工作经历
            PersonalWorkExperienceViewController *PMRVC = [[PersonalWorkExperienceViewController alloc] init];
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:NO];
        } else {
            if ([data[@"user_role"] integerValue] == 1) {
                [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                    [SharedApp showViewController:TabBarTypeOfCompany];
                }];
            } else {
                [DataToolsControl getMyBaseInfoForWorker:^(BOOL requestFlag) {
                    [SharedApp showViewController:TabBarTypeOfPersonal];
                }];
            }
        }
    }
}

- (void)signinLoadData:(NSDictionary *)responseObject {
//    [DataToolsControl dataAnalysisUserInfo:responseObject];
//    IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
//    [self.navigationController pushViewController:IDSVC animated:YES];

    [[TUIKit sharedInstance] initKit:[UD_GetOForK(isIMAppID) integerValue] accountType:UD_GetOForK(isIMAccountType) withConfig:[TUIKitConfig defaultConfig]];
    TIMLoginParam *login_param = [[TIMLoginParam alloc ]init];
    // identifier 为用户名，userSig 为用户登录凭证
    // appidAt3rd 在私有帐号情况下，填写与 sdkAppId 一样
    login_param.identifier = UD_GetOForK(isUserID);
    login_param.userSig = UD_GetOForK(isIMUserSig);
    login_param.appidAt3rd = UD_GetOForK(isIMAppID);
    [[TIMManager sharedInstance] login: login_param succ:^(){
        [DataToolsControl sharedManager].isTIMLoginSuccess = YES;
        NSLog(@"Init Succ");
        //                if ([DataToolsControl sharedManager].deviceToken && [DataToolsControl sharedManager].deviceToken.length) {
        NSData *tokenData = UD_GetOForK(isDeviceToken);
        if (tokenData && tokenData.length) {
            TIMTokenParam *param = [[TIMTokenParam alloc] init];
#if DEBUG
            param.busiId = TIMPushDevID;
#else
            param.busiId = TIMPushReleaseID;
#endif
//                    [param setToken:[DataToolsControl sharedManager].deviceToken];
            [param setToken:UD_GetOForK(isDeviceToken)];
            [[TIMManager sharedInstance] setToken:param succ:^{
                NSLog(@"-----> 上传 token 成功 ");
            } fail:^(int code, NSString *msg) {
                NSLog(@"-----> 上传 token 失败 ");
            }];
        }
    } fail:^(int code, NSString * err) {
        [DataToolsControl sharedManager].isTIMLoginSuccess = NO;
        NSLog(@"Login Failed: %d->%@", code, err);
    }];
    return;


    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phoneTextField.text forKey:@"username"];
    [dic setObject:recordStr forKey:@"password"];

    [BaseNetManager requestWithMethod:POST path:Signin_Pwd_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            [DataToolsControl dataAnalysisUserInfo:responseObject];

            IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
            [self.navigationController pushViewController:IDSVC animated:YES];

            [[TUIKit sharedInstance] initKit:[UD_GetOForK(isIMAppID) integerValue] accountType:UD_GetOForK(isIMAccountType) withConfig:[TUIKitConfig defaultConfig]];
            TIMLoginParam *login_param = [[TIMLoginParam alloc ]init];
            // identifier 为用户名，userSig 为用户登录凭证
            // appidAt3rd 在私有帐号情况下，填写与 sdkAppId 一样
            login_param.identifier = UD_GetOForK(isUserID);
            login_param.userSig = UD_GetOForK(isIMUserSig);
            login_param.appidAt3rd = UD_GetOForK(isIMAppID);
            [[TIMManager sharedInstance] login: login_param succ:^(){
                [DataToolsControl sharedManager].isTIMLoginSuccess = YES;
                NSLog(@"Init Succ");
//                if ([DataToolsControl sharedManager].deviceToken && [DataToolsControl sharedManager].deviceToken.length) {
                NSData *tokenData = UD_GetOForK(isDeviceToken);
                if (tokenData && tokenData.length) {
                    TIMTokenParam *param = [[TIMTokenParam alloc] init];
#if DEBUG
                    param.busiId = TIMPushDevID;
#else
                    param.busiId = TIMPushReleaseID;
#endif
//                    [param setToken:[DataToolsControl sharedManager].deviceToken];
                    [param setToken:UD_GetOForK(isDeviceToken)];
                    [[TIMManager sharedInstance] setToken:param succ:^{
                        NSLog(@"-----> 上传 token 成功 ");
                    } fail:^(int code, NSString *msg) {
                        NSLog(@"-----> 上传 token 失败 ");
                    }];
                }
            } fail:^(int code, NSString * err) {
                [DataToolsControl sharedManager].isTIMLoginSuccess = NO;
                NSLog(@"Login Failed: %d->%@", code, err);
            }];
        }
    } failurBlock:^(NSError *error) {
        [self signinLoadData:@{}];
    }];
}

#pragma mark - Apple 登录 代理方法
#pragma mark - 授权成功的回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization  API_AVAILABLE(ios(13.0)) {
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        
        ASAuthorizationAppleIDCredential * credential = authorization.credential;
        
        // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App 下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
        NSString * userID = credential.user;
        
        // 苹果用户信息 如果授权过，可能无法再次获取该信息
        NSPersonNameComponents * fullName = credential.fullName;
        NSString * email = credential.email;
        
        // 服务器验证需要使用的参数
        NSString * authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding];
        NSString * identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
        
        // 用于判断当前登录的苹果账号是否是一个真实用户，取值有：unsupported、unknown、likelyReal
        ASUserDetectionStatus realUserStatus = credential.realUserStatus;
        
        [[NSUserDefaults standardUserDefaults] setObject:userID forKey:@"appleID"];
        
        
        UD_SetOForK(userID, isOpenWXSigninCode);
        UDSynchronize;

        [DataToolsControl sharedManager].codeRecord = 1;
        [DataToolsControl sharedManager].isApple = YES;
        [DataToolsControl sharedManager].isWXSigninCode = userID;
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationForWXCode object:nil userInfo:@{@"code":userID}];
        NSLog(@"userID: %@", userID);
        NSLog(@"fullName: %@", fullName);
        NSLog(@"email: %@", email);
        NSLog(@"authorizationCode: %@", authorizationCode);
        NSLog(@"identityToken: %@", identityToken);
        NSLog(@"realUserStatus: %@", @(realUserStatus));
    }
    else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]) {
        // 用户登录使用现有的密码凭证
        ASPasswordCredential * passwordCredential = authorization.credential;
        // 密码凭证对象的用户标识 用户的唯一标识
        NSString * user = passwordCredential.user;
        // 密码凭证对象的密码
        NSString * password = passwordCredential.password;
        
        NSLog(@"userID: %@", user);
        NSLog(@"password: %@", password);
        
        UD_SetOForK(user, isOpenWXSigninCode);
        UDSynchronize;

        [DataToolsControl sharedManager].codeRecord = 1;
        [DataToolsControl sharedManager].isApple = YES;

        [DataToolsControl sharedManager].isWXSigninCode = user;
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationForWXCode object:nil userInfo:@{@"code":user}];
        
    }
    
    
}

#pragma mark - 授权回调失败
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error  API_AVAILABLE(ios(13.0)){
    
     NSLog(@"错误信息：%@", error);
     NSString *errorMsg;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            NSLog(@"errorMsg -   %@",errorMsg);
            [self.view makeToast:errorMsg duration:1 position:CSToastPositionCenter];

            break;
            
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            NSLog(@"errorMsg -   %@",errorMsg);
            [self.view makeToast:errorMsg duration:1 position:CSToastPositionCenter];

            break;
            
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            NSLog(@"errorMsg -   %@",errorMsg);
            [self.view makeToast:errorMsg duration:1 position:CSToastPositionCenter];

            break;
            
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            NSLog(@"errorMsg -   %@",errorMsg);
            [self.view makeToast:errorMsg duration:1 position:CSToastPositionCenter];
            break;
            
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            [self.view makeToast:errorMsg duration:1 position:CSToastPositionCenter];
            NSLog(@"errorMsg -   %@",errorMsg);
            break;
                        
        default:
            break;
    }
}


- (void)registerBtnTap {
    NSLog(@"registerBtnTap");
    RegisterViewController *RVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:RVC animated:YES];
}
- (void)captchaSigninBtnTap {
    SigninForCaptchaViewController *SCVC = [[SigninForCaptchaViewController alloc] init];
    [self.navigationController pushViewController:SCVC animated:YES];
}
- (void)forgetPwdBtnTap {
    NSLog(@"forgetPwdBtnTap");
    FindPwdViewController *RPVC = [[FindPwdViewController alloc] init];
    [self.navigationController pushViewController:RPVC animated:YES];
}
- (void)customBackButtonTap {
    self.signin(NO);
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)closeBtnTap {
    if (UD_GetOForK(isUserRole) && [UD_GetOForK(isUserRole) isEqualToString:@"1"]) {
        [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
            [SharedApp showViewController:TabBarTypeOfCompany];
        }];
    } else {
        [DataToolsControl getMyBaseInfoForWorker:^(BOOL requestFlag) {
            [SharedApp showViewController:TabBarTypeOfPersonal];
        }];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [UIToolsControl resignFirstResponderForTextFieldArray:@[phoneTextField, passwordTextField]];
}

@end
